#!/usr/bin/env python
# coding: utf-8

import os
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

##调取若干模型
from sklearn import linear_model
from sklearn.linear_model import LinearRegression,SGDRegressor
from sklearn import preprocessing
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor,GradientBoostingRegressor

import xgboost as xgb
from sklearn.model_selection import GridSearchCV,cross_val_score,StratifiedKFold,train_test_split
from sklearn.metrics import mean_squared_error, mean_absolute_error

# cur_path = os.getcwd()
cur_path = 'F:/QCH_ignition_model'
os.chdir( cur_path )

# os.chdir('F:/QCH_ignition_model/cfx/0430')

CFX_Data = pd.read_csv(cur_path +'/success_export.csv',sep=',')      #,index_col=0
print('CFX data shape:',CFX_Data.shape)
colnames = CFX_Data.columns.values.tolist()
CFX_Data.info()
#print(colnames) 
'''
0 1 2   
X Y Z

22-24 25-27 28-30 31-33
u     v     w     abs(Velosity)

3-5 12-14 6-8     9-11  15 
CH4 O2    Density Visco Tem  

16-18
Turbulence Eddy Dissipation

19-21
Turbulence Kinetic Energy

'''


input_colnames = ['X [ m ]', 'Y [ m ]', 'Z [ m ]']
output_colnames =['Velocity.Trnavg [ m s^-1 ]'] 
X_data = CFX_Data[input_colnames]
Y_data = CFX_Data[output_colnames[0]]
print('X train shape:',X_data.shape)
X_data.info()


#统计函数
def get_info(data):
    print('最小值：',np.min(data))
    print('最大值：',np.max(data))
    print('平均值:',np.mean(data))
    print('方差:',np.var(data))



print('训练集分布情况')
get_info(Y_data)
#Y_data.info
#Y_data.info



#查看统计分布
plt.hist(Y_data)
plt.show()
plt.close()

#去掉NaN
X_data = X_data.fillna(-1)
Y_data = Y_data.fillna(-1)

##若干模型函数
def build_model_xgb(x_train,y_train):
    model = xgb.XGBRegressor(n_estimators=150, learning_rate=0.1, gamma=0, subsample=0.8,        colsample_bytree=0.9, max_depth=9) 
    objective ='reg:squarederror'
    model.fit(x_train, y_train)
    return model



import re
regex = re.compile(r"\[|\]|<", re.IGNORECASE)
X_data.columns = [regex.sub("_", col) if any(x in str(col) for x in set(('[', ']', '<'))) \
                        else col for col in X_data.columns.values]
model=build_model_xgb(X_data,Y_data)
# model.fit(X_data,Y_data)
pred_train_xgb=model.predict(X_data)
score_train = mean_absolute_error(Y_data,pred_train_xgb)


# from sklearn.cross_validation import KFold, cross_val_score
# k_fold = KFold(len(y), n_folds=5, shuffle=True, random_state=0)
# clf = '<any classifier>'
# print(cross_val_score(clf, X_data, Y_data, cv=k_fold, n_jobs=1))

# from sklearn.utils.multiclass import type_of_target
# type_of_target(Y_data)


# ##五折交叉验证查看参数效果xgb
# scores_train = []
# scores = []
# sk = StratifiedKFold(n_splits=2)#shuffle=True,random_state=0
# i=0
# for train_ind,test_ind in sk.split(X_data,Y_data):
#     i = i+1
#     train_x=X_data.iloc[train_ind].values
#     train_y=Y_data.iloc[train_ind]
#     test_x=X_data.iloc[test_ind].values
#     test_y=Y_data.iloc[test_ind]

#     model=build_model_xgb(train_x,train_y)
#     model.fit(train_x,train_y)
#     pred_train_xgb=model.predict(train_x)
#     pred_xgb=model.predict(test_x)
    
#     score_train = mean_absolute_error(train_y,pred_train_xgb)
#     scores_train.append(score_train)
#     score = mean_absolute_error(test_y,pred_xgb)
#     scores.append(score)

# print('Train mae:',np.mean(score_train))
# print('Val mae',np.mean(scores))






